package com.frxuexi.lib_base

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File

object DownloadUtil {
    fun download(url:String,file:File):Flow<UiState>{
        return flow {
            val request = Request.Builder().url(url).get().build()
            val response = OkHttpClient.Builder().build().newCall(request).execute()
            if(response.isSuccessful){
                file.outputStream()?.let {os->
                    val stream = response.body?.byteStream()
                    var len=0
                    val array = ByteArray(DEFAULT_BUFFER_SIZE)
                    while (stream?.read(array).also { len=it!! }!=-1){
                        os.write(array,0,len)
                    }
                    os.flush()
                    os.close()
                    emit(UiState.onSuccess("",RequestType.DOWNLOAD))
                }
            }else{
                emit(UiState.onError("下载失败"))
            }
        }
    }
}